const express = require('express');
const { buildSchema } = require('graphql');
const { graphqlHTTP } = require('express-graphql');
const mongoInstance = require('./db');

const schema = buildSchema(`
  input UserInput {
    "姓名"
    name: String
    "年龄"
    age: Int
  }
  type User {
    "ID"
    id: ID,
    "姓名"
    name: String,
    "年龄"
    age: Int
  }
  type Query {
    "获取所有用户"
    getUsers: [User]
    "获取单个用户信息"
    getUser(id: ID!): User
  }
  type Mutation {
    "创建用户"
    createUser(user: UserInput): Boolean
    "更新用户"
    updateUser(id: ID!, user: UserInput): Boolean
    "删除用户"
    deleteUser(id: ID!): Boolean
  }
`);

const root = {
  async getUsers() {
    const result = await mongoInstance.find('user', {});
    return result.map((item) => {
      const { _id, ...rest } = item;
      return {
        id: _id,
        ...rest,
      };
    });
  },
  async getUser({ id }) {
    const { _id, ...rest } = await mongoInstance.findOne('user', {
      _id: mongoInstance.getObjectId(id),
    });
    return {
      id: _id,
      ...rest,
    };
  },
  async createUser({ user }) {
    const { acknowledged } = await mongoInstance.insertOne('user', user);
    return acknowledged;
  },
  async updateUser({ id, user }) {
    const { acknowledged } = await mongoInstance.updateOne(
      'user',
      {
        _id: mongoInstance.getObjectId(id),
      },
      {
        $set: user,
      }
    );
    return acknowledged;
  },
  async deleteUser({ id }) {
    const { acknowledged } = await mongoInstance.deleteOne('user', {
      _id: mongoInstance.getObjectId(id),
    });
    return acknowledged;
  },
};

const app = express();

app.use(
  '/api/graphql',
  graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true,
  })
);

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(express.static('public'));

app.listen(3000, () => {
  console.log('server is running in http://localhost:3000/api/graphql');
});
